package com.hliushi.mp.web;

import com.hliushi.mp.service.StationService;
import com.hliushi.mp.util.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试 ApplicationContext的getBean方法与@Resource | @Autowired的区别
 *
 * @author llhuang10
 * @date 2021/10/9 8:58
 */
@Slf4j
@RestController
@RequestMapping("/getBean")
public class GetBeanController {

    /**
     * 测试结果
     * 前提条件: 将StationServiceImpl这个类上加了两个注解, 其中@Scope("prototype")开启多例模式
     *
     * @Service
     * @Scope("prototype") // 设置这个对象为多例模式
     * public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements StationService {}
     * <p>
     * 使用JMeter使用模拟多用户多个线程进行测试,
     * 在ResourceController使用@Resource依赖注入的方式给stationService赋值
     * test01()和test02()方法打印的是同一个对象, stationService的hashCode都是同一个值
     * <p>
     * http-nio-8080-exec-6 com.hliushi.mp.service.impl.StationServiceImpl@79e553a4
     * http-nio-8080-exec-7 com.hliushi.mp.service.impl.StationServiceImpl@79e553a4
     * http-nio-8080-exec-9 com.hliushi.mp.service.impl.StationServiceImpl@79e553a4
     * http-nio-8080-exec-2 com.hliushi.mp.service.impl.StationServiceImpl@79e553a4
     * <p>
     * 而在GetBeanController使用SpringContextHolder.getBean(StationService.class)方式给stationService赋值
     * test01()和test02()方法打印的不是同一个对象!!!, 每个线程都自己对应了一个对象, 它们的hashCode的值都不是一样的
     * <p>
     * http-nio-8080-exec-1 com.hliushi.mp.service.impl.StationServiceImpl@76602a31
     * http-nio-8080-exec-2 com.hliushi.mp.service.impl.StationServiceImpl@36f1ea02
     * http-nio-8080-exec-4 com.hliushi.mp.service.impl.StationServiceImpl@525b6269
     * http-nio-8080-exec-5 com.hliushi.mp.service.impl.StationServiceImpl@1ee9f636
     */


    private StationService stationService;

    @GetMapping("/test01")
    public ResponseEntity<String> test01() {
        stationService = SpringContextHolder.getBean(StationService.class);
        System.out.println(Thread.currentThread().getName() + " " + stationService.toString());
        // log.info(stationService.toString());
        return ResponseEntity.ok("test01");
    }

    @GetMapping("/test02")
    public ResponseEntity<String> test02() {
        stationService = SpringContextHolder.getBean(StationService.class);
        System.out.println(Thread.currentThread().getName() + " " + stationService.toString());
        // log.info(stationService.toString());
        return ResponseEntity.ok("test02");
    }

}
